package main.java.thread;

/**
 * 有效缩小同步范围可以在保证并发安全的前提下尽可能的提高并发效率
 */
public class SyncDemo2 {
    public static void main(String[] args) {
        Shop shop1 = new Shop();
        Shop shop2 = new Shop();
        Thread r1 = new Thread(){
            public void run(){
                shop1.buy();
            }
        };
        Thread r2 = new Thread(){
            public void run(){
                shop2.buy();
            }
        };
        Thread r3 = new Thread(){
            public void run(){
                shop2.buy();
            }
        };
        r1.start();
        r2.start();
        r3.start();
    }
}
class Shop{
   public void buy(){
       try{
           Thread t =Thread.currentThread();
           System.out.println(t.getName()+"正在挑衣服");
           Thread.sleep(5000);
           /*
           * 通常同步监视器对象synchronized：临界资源
           * this：当前对象，当前线程所操作的对象
           * 换句话说 抢谁锁谁
            */
           synchronized (this){
               System.out.println(t.getName() + "正在试衣服");
               Thread.sleep(5000);
           }
           System.out.println(t.getName()+"结账离开");
       }catch (InterruptedException e){
           e.printStackTrace();
       }
   }
}